"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/shared.ts
var _parser = require('@babel/parser'); var parser = _interopRequireWildcard(_parser);
var _generator = require('@babel/generator'); var _generator2 = _interopRequireDefault(_generator);
var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);
var _paramcase = require('param-case');
var _module = require('module');
var _path = require('path'); var path = _interopRequireWildcard(_path);
var _fs = require('fs'); var fs = _interopRequireWildcard(_fs);
var generate = typeof _generator2.default === "function" ? _generator2.default : _generator2.default.default;
var createRequire = _module.Module.createRequire || _module.Module.createRequireFromPath;
function getType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}
var identity = (v) => v;
var isArray = Array.isArray;
var isString = (obj) => typeof obj === "string";
var isBoolean = (obj) => typeof obj === "boolean";
var isRegExp = (obj) => getType(obj) === "RegExp";
function parseImportModule(code, libList, command) {
  const ast = parser.parse(code, {
    sourceType: "module",
    plugins: [
      // enable jsx and flow syntax
      "jsx"
    ]
  });
  const astBody = ast.program.body;
  const importMaps = {};
  const toBeRemoveIndex = [];
  let newImportStatement = "";
  astBody.forEach((astNode, index) => {
    if (astNode.type !== "ImportDeclaration") {
      return;
    }
    const libName = astNode.source.value;
    const matchLib = libList.find((lib) => lib.libName === libName);
    if (!matchLib) {
      return;
    }
    if (astNode.specifiers.length === 0) {
      warn(`Can't transform ${generate(astNode).code}`);
      return;
    }
    const {
      camel2DashComponentName = true,
      libDirectory = "es",
      replaceOldImport = command === "build",
      nameFormatter = identity
    } = matchLib;
    astNode.specifiers.forEach((item) => {
      if (item.type === "ImportNamespaceSpecifier") {
        warn(`Can't transform ${generate(astNode).code}`);
        return;
      }
      const name = item.type === "ImportDefaultSpecifier" ? "default" : item.imported.type === "Identifier" ? item.imported.name : item.imported.value;
      const localName = item.local.name;
      const libDir = libDirectory ? `${libDirectory}/` : "";
      if (replaceOldImport) {
        const finalName = nameFormatter(
          camel2DashComponentName ? _paramcase.paramCase.call(void 0, name) : name,
          name
        );
        newImportStatement += `import ${localName} from '${libName}/${libDir}${finalName}';`;
        toBeRemoveIndex.push(index);
      }
      if (importMaps[libName]) {
        importMaps[libName].push(name);
      } else {
        importMaps[libName] = [name];
      }
    });
  });
  ast.program.body = astBody.filter((item, index) => !toBeRemoveIndex.includes(index));
  let codeRemoveOriginImport = generate(ast).code;
  codeRemoveOriginImport = `${newImportStatement} ; ${codeRemoveOriginImport}`;
  return { importMaps, codeRemoveOriginImport };
}
var codeIncludesLibraryName = (code, libList) => {
  return !libList.every(({ libName }) => {
    return !new RegExp(`('${libName}')|("${libName}")`).test(code);
  });
};
var stylePathNotFoundHandler = (stylePath, ignoreStylePathNotFound) => {
  if (ignoreStylePathNotFound) {
    let stylePathExists = true;
    try {
      createRequire(process.cwd() + path.sep).resolve(stylePath);
    } catch (error) {
      stylePathExists = _optionalChain([error, 'optionalAccess', _ => _.code]) !== "MODULE_NOT_FOUND";
    }
    if (!stylePathExists) {
      const fullStylePath = path.resolve(process.cwd(), "node_modules", stylePath);
      const lastPath = fullStylePath.split("/").pop();
      if (!_optionalChain([lastPath, 'optionalAccess', _2 => _2.includes, 'call', _3 => _3(".")])) {
        const possibleEndWithsPaths = [
          "/index.js",
          "/index.mjs",
          ".js",
          ".mjs"
        ];
        if (possibleEndWithsPaths.some((p) => fs.existsSync(fullStylePath + p))) {
          stylePathExists = true;
        }
      }
    }
    if (stylePathExists) {
      return `import '${stylePath}';`;
    } else {
      warn(`${stylePath} is not found!`);
      return "";
    }
  }
  return `import '${stylePath}';`;
};
var stylePathHandler = (stylePath, ignoreStylePathNotFound = true) => {
  let str = "";
  if (isString(stylePath) && stylePath) {
    str += stylePathNotFoundHandler(stylePath, ignoreStylePathNotFound);
  } else if (isArray(stylePath)) {
    stylePath.forEach((item) => {
      str += stylePathNotFoundHandler(item, ignoreStylePathNotFound);
    });
  }
  return str;
};
var analyzeCode = (code, impConfig, command, ignoreStylePathNotFound) => {
  const { importMaps, codeRemoveOriginImport } = parseImportModule(code, impConfig.libList, command);
  let importStr = "";
  impConfig.libList.forEach(({ libName, style = () => false, camel2DashComponentName = true }) => {
    if (importMaps[libName]) {
      importMaps[libName].forEach((item) => {
        if (camel2DashComponentName) {
          item = _paramcase.paramCase.call(void 0, item);
        }
        let stylePath = style(item);
        const styleImportString = stylePathHandler(stylePath, ignoreStylePathNotFound);
        importStr += styleImportString;
      });
    }
  });
  return {
    importStr,
    codeRemoveOriginImport
  };
};
var log = (...args) => {
  args[0] = `${_chalk2.default.green("[vite-plugin-auto-imp]")} ${args[0]}`;
  console.log(...args);
};
var warn = (...args) => {
  args[0] = `${_chalk2.default.yellow("[vite-plugin-auto-imp]")} ${args[0]}`;
  console.log(...args);
};
var isTranspileDependencies = (transpileDependencies, id) => {
  if (isBoolean(transpileDependencies)) return transpileDependencies;
  if (isArray(transpileDependencies)) {
    for (const item of transpileDependencies) {
      if (isString(item) && id.includes(item) || isRegExp(item) && item.test(id)) {
        return true;
      }
    }
  }
  return false;
};

// src/index.ts


// src/resolvers/antd-mobile.ts
var AntdMobileReactResolver = {
  libName: "antd-mobile",
  libDirectory: "es/components"
};

// src/resolvers/antd.ts
var AntdResolver = {
  libName: "antd",
  style(name) {
    return `antd/es/${name}/style/css.js`;
  }
};

// src/resolvers/antdv.ts
var AntDesignVueResolver = {
  libName: "ant-design-vue",
  style: (name) => `ant-design-vue/es/${name}/style/css.js`
};

// src/resolvers/arco-design-react.ts
var ArcoDesignReactResolver = {
  libName: "@arco-design/web-react",
  replaceOldImport: false,
  style: (name) => `@arco-design/web-react/es/${name}/style/css.js`
};

// src/resolvers/arco-design-vue.ts
var _pascalcase = require('pascal-case');
var matchComponents = [
  {
    pattern: /^AnchorLink$/,
    componentDir: "anchor"
  },
  {
    pattern: /^AvatarGroup$/,
    componentDir: "avatar"
  },
  {
    pattern: /^BreadcrumbItem$/,
    componentDir: "breadcrumb"
  },
  {
    pattern: /^ButtonGroup$/,
    componentDir: "button"
  },
  {
    pattern: /^(CardMeta|CardGrid)$/,
    componentDir: "card"
  },
  {
    pattern: /^CarouselItem$/,
    componentDir: "carousel"
  },
  {
    pattern: /^CheckboxGroup$/,
    componentDir: "checkbox"
  },
  {
    pattern: /^CollapseItem$/,
    componentDir: "collapse"
  },
  {
    pattern: /^(WeekPicker|MonthPicker|YearPicker|QuarterPicker|RangePicker)$/,
    componentDir: "date-picker"
  },
  {
    pattern: /^(Doption|Dgroup|Dsubmenu)$/,
    componentDir: "dropdown"
  },
  {
    pattern: /^FormItem$/,
    componentDir: "form"
  },
  {
    pattern: /^(Col|Row)$/,
    componentDir: "grid"
  },
  {
    pattern: /^(ImagePreview|ImagePreviewGroup)$/,
    componentDir: "image"
  },
  {
    pattern: /^(InputGroup|InputSearch|InputPassword)$/,
    componentDir: "input"
  },
  {
    pattern: /^(LayoutHeader|LayoutContent|LayoutFooter|LayoutSider)$/,
    componentDir: "layout"
  },
  {
    pattern: /^(ListItem|ListItemMeta)$/,
    componentDir: "list"
  },
  {
    pattern: /^(MenuItem|MenuItemGroup|SubMenu)$/,
    componentDir: "menu"
  },
  {
    pattern: /^RadioGroup$/,
    componentDir: "radio"
  },
  {
    pattern: /^(Option|Optgroup)$/,
    componentDir: "select"
  },
  {
    pattern: /^(SkeletonLine|SkeletonShape)$/,
    componentDir: "table"
  },
  {
    pattern: /^Countdown$/,
    componentDir: "statistic"
  },
  {
    pattern: /^Step$/,
    componentDir: "steps"
  },
  {
    pattern: /^(Thead|Td|Th|Tr|Tbody|TableColumn)$/,
    componentDir: "table"
  },
  {
    pattern: /^TabPane$/,
    componentDir: "tabs"
  },
  {
    pattern: /^TimelineItem$/,
    componentDir: "timeline"
  },
  {
    pattern: /^(TypographyParagraph|TypographyTitle|TypographyText)$/,
    componentDir: "typography"
  }
];
var notComponents = ["AddI18nMessages", "GetLocale", "UseLocale"];
var ArcoDesignVueResolver = {
  libName: "@arco-design/web-vue",
  replaceOldImport: false,
  style(name) {
    let styleDir = name;
    for (const item of notComponents) {
      if (item === _pascalcase.pascalCase.call(void 0, name)) {
        return false;
      }
    }
    for (const item of matchComponents) {
      if (item.pattern.test(_pascalcase.pascalCase.call(void 0, name))) {
        styleDir = item.componentDir;
        break;
      }
    }
    return `@arco-design/web-vue/es/${styleDir}/style/css.js`;
  }
};

// src/resolvers/element-plus.ts
var ElementPlusResolver = {
  libName: "element-plus",
  libDirectory: "es/components",
  nameFormatter: (name) => {
    return name.replace("el-", "");
  },
  style: (name) => {
    if (["el-config-provider", "effect"].includes(name)) return false;
    return `element-plus/es/components/${name.replace("el-", "")}/style/css.js`;
  }
};

// src/resolvers/element-ui.ts

var components = [
  "ElAlert",
  "ElAside",
  "ElAutocomplete",
  "ElBadge",
  "ElBreadcrumb",
  "ElBreadcrumbItem",
  "ElButton",
  "ElButtonGroup",
  "ElCard",
  "ElCarousel",
  "ElCarouselItem",
  "ElCascader",
  "ElCheckbox",
  "ElCheckboxButton",
  "ElCheckboxGroup",
  "ElCol",
  "ElCollapse",
  "ElCollapseItem",
  "ElColorPicker",
  "ElContainer",
  "ElDatePicker",
  "ElDialog",
  "ElDropdown",
  "ElDropdownItem",
  "ElDropdownMenu",
  "ElFooter",
  "ElForm",
  "ElFormItem",
  "ElHeader",
  "ElInput",
  "ElInputNumber",
  "ElLoading",
  "ElMain",
  "ElMenu",
  "ElMenuItem",
  "ElMenuItemGroup",
  "ElMessage",
  "ElMessageBox",
  "ElNotification",
  "ElOption",
  "ElOptionGroup",
  "ElPagination",
  "ElPopover",
  "ElProgress",
  "ElRate",
  "ElRadio",
  "ElRadioButton",
  "ElRadioGroup",
  "ElRow",
  "ElSelect",
  "ElSlider",
  "ElStep",
  "ElSteps",
  "ElSubmenu",
  "ElSwitch",
  "ElTable",
  "ElTableColumn",
  "ElTag",
  "ElTabs",
  "ElTabPane",
  "ElTimeline",
  "ElTimelineItem",
  "ElTimePicker",
  "ElTimeSelect",
  "ElTooltip",
  "ElTransfer",
  "ElTree",
  "ElUpload",
  "ElLink",
  "ElDivider",
  "ElIcon",
  "ElCalendar",
  "ElImage",
  "ElBacktop",
  "ElInfiniteScroll",
  "ElPageHeader",
  "ElAvatar",
  "ElDrawer",
  "ElPopconfirm",
  "ElSkeleton",
  "ElSkeletonItem",
  "ElCascaderPanel",
  "ElEmpty",
  "ElSpinner",
  "ElDescriptions",
  "ElDescriptionsItem",
  "ElResult"
];
var ElementUIResolver = {
  libName: "element-ui",
  libDirectory: "lib",
  style(name) {
    if (components.includes(_pascalcase.pascalCase.call(void 0, `el-${name}`))) {
      return `element-ui/lib/theme-chalk/${name}.css`;
    }
    return false;
  }
};

// src/resolvers/view-ui.ts
var ViewUIResolver = {
  libName: "view-design",
  libDirectory: "src/components",
  replaceOldImport: true
};

// src/resolvers/lodash.ts
var LodashResolver = {
  libName: "lodash",
  libDirectory: "",
  camel2DashComponentName: false
};

// src/resolvers/underscore.ts
var UnderScoreResolver = {
  libName: "underscore",
  libDirectory: "module",
  camel2DashComponentName: false
};

// src/resolvers/vant.ts
var VantResolver = {
  libName: "vant",
  replaceOldImport: false,
  style: (name) => `vant/es/${name}/style/index`
};

// src/resolvers/vuetify.ts
var VuetifyResolver = {
  libName: "vuetify",
  libDirectory: "lib/components",
  replaceOldImport: true,
  style: () => false,
  camel2DashComponentName: false
};

// src/resolvers/mooli-mobile.ts
var MooliMobileResolver = {
  libName: "mooli-mobile",
  style(name) {
    const getStyles = (name2) => {
      if (typeof name2 === "string") {
        return [`mooli-mobile/es/${name2}/style/index.css`];
      }
      return name2.map((n) => `mooli-mobile/es/${n}/style/index.css`);
    };
    const css = [`mooli-mobile/es/${name}/style/index.css`];
    if (/action-sheet/.test(name)) {
      return css.concat(getStyles(["popup", "icon", "button", "loading"]));
    }
    if (/b-address/.test(name)) {
      return css.concat(getStyles(["tabs", "sticky", "info", "loading"]));
    }
    if (/b-button/.test(name)) {
      return css.concat(getStyles(["button", "loading", "icon"]));
    }
    if (/b-camera/.test(name)) {
      return css.concat(getStyles(["camera"]));
    }
    if (/b-captcha/.test(name)) {
      return css.concat(getStyles(["captcha", "overlay", "popup", "toast", "icon", "loading"]));
    }
    if (/b-input/.test(name)) {
      return css.concat(getStyles(["field", "cell", "icon"]));
    }
    if (/b-uploader/.test(name)) {
      return css.concat(getStyles(["uploader", "toast", "icon", "loading", "image", "image-preview", "swiper", "popup"]));
    }
    if (/button/.test(name)) {
      return css.concat(getStyles(["loading", "icon"]));
    }
    if (/captcha/.test(name)) {
      return css.concat(getStyles(["loading", "overlay"]));
    }
    if (/cascader/.test(name)) {
      return css.concat(getStyles(["tabs", "icon", "loading", "sticky", "info"]));
    }
    if (/cell/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/checkbox/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/collapse/.test(name)) {
      return css.concat(getStyles(["cell"]));
    }
    if (/datetime-picker/.test(name)) {
      return css.concat(getStyles(["picker", "loading"]));
    }
    if (/dialog/.test(name)) {
      return css.concat(getStyles(["button", "loading", "icon"]));
    }
    if (/field/.test(name)) {
      return css.concat(getStyles(["cell", "icon"]));
    }
    if (/image/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/image-preview/.test(name)) {
      return css.concat(getStyles(["swiper", "icon", "image", "popup"]));
    }
    if (/list/.test(name)) {
      return css.concat(getStyles(["loading"]));
    }
    if (/notice-bar/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/notify/.test(name)) {
      return css.concat(getStyles(["popup", "icon"]));
    }
    if (/number-keyboard/.test(name)) {
      return css.concat(getStyles(["popup", "icon"]));
    }
    if (/picker/.test(name)) {
      return css.concat(getStyles(["loading"]));
    }
    if (/popup/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/pull-refresh/.test(name)) {
      return css.concat(getStyles(["loading"]));
    }
    if (/radio/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/search/.test(name)) {
      return css.concat(getStyles(["field", "cell", "icon"]));
    }
    if (/select/.test(name)) {
      return css.concat(getStyles(["search", "field", "cell", "icon"]));
    }
    if (/swiper/.test(name)) {
      return css.concat(getStyles(["icon"]));
    }
    if (/switch/.test(name)) {
      return css.concat(getStyles(["loading"]));
    }
    if (/tabs/.test(name)) {
      return css.concat(getStyles(["sticky", "info"]));
    }
    if (/toast/.test(name)) {
      return css.concat(getStyles(["icon", "loading"]));
    }
    if (/uploader/.test(name)) {
      return css.concat(getStyles(["icon", "loading", "image", "image-preview", "swiper", "popup"]));
    }
    return css;
  }
};

// src/resolvers/fexd-mobile.ts
var notComponents2 = [
  "cloneFC",
  "createFC",
  "createForm",
  "createModalAPI",
  "createModalAPI",
  "modalConflict",
  "modalStore",
  "uniqueId",
  "uniqueId",
  "useForcedUpdate",
  "useIOControl",
  "usePickerProps",
  "useSelectionFieldProps",
  "useSize",
  "useTextFieldProps",
  "useThrottleFn",
  "useTouch",
  "useTween"
];
var FexdMobileResolver = {
  libName: "@fexd/mobile",
  replaceOldImport: false,
  camel2DashComponentName: false,
  style(name) {
    let styleDir = name;
    for (const item of notComponents2) {
      if (item === name) {
        return false;
      }
    }
    return `@fexd/mobile/es/exports/${styleDir}/style.less`;
  }
};

// src/resolvers/fexd-mobile-router5.ts
var FexdMobileRouter5Resolver = {
  libName: "@fexd/mobile-router5",
  replaceOldImport: false,
  camel2DashComponentName: false,
  style(name) {
    return `@fexd/mobile-router5/es/exports/${name}/style.less`;
  }
};

// src/resolvers/fexd-tools.ts
var FexdToolsResolver = {
  libName: "@fexd/tools",
  libDirectory: "es",
  replaceOldImport: false,
  camel2DashComponentName: false
};

// src/resolvers/arco-design-mobile-react.ts
var ArcoDesignMobileReactResolver = {
  libName: "@arco-design/mobile-react",
  replaceOldImport: false,
  style: (name) => `@arco-design/mobile-react/esm/${name}/style/css/`
};

// src/resolvers/ahooks.ts
var AhooksResolver = {
  libName: "ahooks",
  libDirectory: "es",
  camel2DashComponentName: false
};

// src/resolvers/index.ts
var defaultLibList = [
  AntdMobileReactResolver,
  AntdResolver,
  AntDesignVueResolver,
  ArcoDesignReactResolver,
  ArcoDesignVueResolver,
  ArcoDesignMobileReactResolver,
  ElementPlusResolver,
  ElementUIResolver,
  ViewUIResolver,
  LodashResolver,
  UnderScoreResolver,
  VantResolver,
  VuetifyResolver,
  MooliMobileResolver,
  FexdMobileResolver,
  FexdMobileRouter5Resolver,
  FexdToolsResolver,
  AhooksResolver
];
var resolvers_default = defaultLibList;

// src/index.ts


var optionsCheck = (options) => {
  if (_optionalChain([options, 'optionalAccess', _4 => _4.libList]) && !Array.isArray(_optionalChain([options, 'optionalAccess', _5 => _5.libList]))) {
    log(_chalk2.default.yellow(`libList is Array, please check your options!`));
    return false;
  }
  return true;
};
function vitePluginImp(userConfig = {}) {
  let viteConfig;
  let config;
  let isSourcemap = false;
  const name = "vite-plugin-auto-imp";
  if (!optionsCheck(userConfig)) {
    return { name };
  }
  return {
    name,
    async configResolved(resolvedConfig) {
      viteConfig = resolvedConfig;
      isSourcemap = !!_optionalChain([viteConfig, 'access', _6 => _6.build, 'optionalAccess', _7 => _7.sourcemap]);
      config = Object.assign({
        libList: [],
        exclude: [],
        removeOriginImport: viteConfig.command === "build",
        ignoreStylePathNotFound: viteConfig.command === "serve"
      }, userConfig);
      const libListNameSet = new Set(config.libList.map((lib) => lib.libName));
      let defaultLibFilteredList = resolvers_default.filter((lib) => !_optionalChain([config, 'access', _8 => _8.exclude, 'optionalAccess', _9 => _9.includes, 'call', _10 => _10(lib.libName)]));
      const userPkgPath = path.default.resolve(viteConfig.root, "package.json");
      if (fs.default.existsSync(userPkgPath)) {
        const userPkg = JSON.parse(fs.default.readFileSync(userPkgPath, "utf8"));
        if (_optionalChain([userPkg, 'optionalAccess', _11 => _11.dependencies])) {
          defaultLibFilteredList = defaultLibFilteredList.filter((item) => _optionalChain([userPkg, 'optionalAccess', _12 => _12.dependencies, 'optionalAccess', _13 => _13[item.libName]]));
        }
      }
      defaultLibFilteredList.forEach((defaultLib) => {
        if (!libListNameSet.has(defaultLib.libName)) {
          _optionalChain([config, 'access', _14 => _14.libList, 'optionalAccess', _15 => _15.push, 'call', _16 => _16(defaultLib)]);
          libListNameSet.add(defaultLib.libName);
        }
      });
    },
    transform(code, id) {
      const { transpileDependencies = false, removeOriginImport } = config;
      if ((!/(node_modules)/.test(id) || isTranspileDependencies(transpileDependencies, id)) && codeIncludesLibraryName(code, config.libList)) {
        const sourcemap = _optionalChain([this, 'optionalAccess', _17 => _17.getCombinedSourcemap, 'call', _18 => _18()]);
        const { importStr, codeRemoveOriginImport } = analyzeCode(code, config, "build", config.ignoreStylePathNotFound);
        return {
          code: `${importStr};${removeOriginImport ? codeRemoveOriginImport : code}`,
          map: isSourcemap ? sourcemap : null
        };
      }
      return {
        code,
        map: null
      };
    }
  };
}


exports.default = vitePluginImp;
